#ifndef PLANTUMLGENERATERTASK_H
#define PLANTUMLGENERATERTASK_H

#include "imagehelper.h"

#include <QDebug>
#include <QEventLoop>
#include <QObject>
#include <QPixmap>
#include <QProcess>
#include <QRunnable>

class PlantUMLGeneraterTask : public QObject, public QRunnable
{
    Q_OBJECT
public:
    explicit PlantUMLGeneraterTask(QObject *parent = nullptr) : QObject(parent) , QRunnable()
    {
        setAutoDelete(true);
    }
    void setGeneraterArguments(QString plantUmlPath, QString type, QString content, QSize pixSize)
    {
        m_pixSize = pixSize;
        m_plantUmlPath = plantUmlPath;
        m_TaskType = type;
        m_TaskContent = content;

       // 1. 预准备需要执行的参数
        m_runArguements << "-jar" << m_plantUmlPath
                        << QString("-t%1").arg(m_TaskType)
                        << "-charset" << "UTF-8" << "-pipe";
    }

signals:
    void generated(const QByteArray data);

public slots:

    // QRunnable interface
public:
    void run() override
    {
        qDebug() << "已执行 run";

        // 1. 启动进程
        m_TaskProcess.start("java", m_runArguements);

        // 2. 等待启动进程完毕
        if (!m_TaskProcess.waitForStarted()) {
            qDebug() << "等待启动超时";
            return;
        }

        // 3. 向进程写入管道数据
        m_TaskProcess.write(m_TaskContent.toUtf8());
        m_TaskProcess.closeWriteChannel();

        // 4. 等待进程执行完成
        if (!m_TaskProcess.waitForFinished()) {
            qDebug() << "等待执行结束超时";
            return;
        }
        // 读取数据
        auto data = m_TaskProcess.readAllStandardOutput();
        // if (m_TaskType == "png"){
        //     m_umlImage.loadFromData(data);
        // } else {
        //     m_umlImage = ImageHelper::pixmapFromSvgString(m_pixSize, data);
        // }
        emit generated(data);

        qDebug() << "已执行 run 完成";
    }

private:
    QString m_plantUmlPath;
    QString m_TaskType;
    QString m_TaskContent;
    QSize   m_pixSize;

    QStringList m_runArguements;

    QPixmap m_umlImage;
    QProcess m_TaskProcess;
};

#endif // PLANTUMLGENERATERTASK_H
